package com.lechi.web.server.connect;

import com.lechi.iot.netty.device.TcpDeviceChannel;
import com.lechi.web.constants.AppCmdConstants;
import com.lechi.web.constants.Constants;
import com.lechi.web.framework.util.GuavaCacheUtil;
import com.lechi.web.server.handle.BaseWeatherInboundHandle;
import com.lechi.web.service.impl.IotDeviceCommond;
import com.lechi.web.util.LeChiCacheUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.Optional;

/**
 * 服务端链接管理器,处理接受数据
 */
@Slf4j
@Sharable
public class TcpServerConnect extends ChannelInboundHandlerAdapter implements BaseWeatherInboundHandle {

    private final String protocol;

    public TcpServerConnect(String protocol) {
        this.protocol = protocol;
    }
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        ctx.fireChannelActive();
        if (Objects.nonNull(channel.remoteAddress())) {
            String hostName = getHostName(ctx);
            log.error("网关协议{}和完整设备地址：{}, 缓存地址：{}建立链接", this.protocol, channel.remoteAddress().toString(), hostName);
            LeChiCacheUtil.getTcpChannelMap().put(hostName, new TcpDeviceChannel(channel));
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        ctx.fireChannelInactive();
        Channel channel = ctx.channel();
        if (Objects.nonNull(channel) && Objects.nonNull(channel.remoteAddress())) {
            String hostName = getHostName(ctx);
            String deviceSn = GuavaCacheUtil.getBiDeviceSnAndIPMap().inverse().get(hostName);
            log.error("网关协议{}下设备序列号或设备ID：{}和设备接入地址：{}断开链接！", this.protocol, deviceSn, channel.remoteAddress().toString());
            if (Constants.ANDROID_TCP.equals(protocol)) {
                Optional.ofNullable(LeChiCacheUtil.getTcpChannelMap().get(hostName)).ifPresent(androidChannel -> {
                    IotDeviceCommond.commond(deviceSn, AppCmdConstants.STOPED);
                });
            }
            LeChiCacheUtil.getTcpChannelMap().remove(hostName);
            //连接断开后的最后处理
            ctx.pipeline().remove(ctx.handler());
            ctx.deregister();
            ctx.close();
        }
    }
}
